package com.a2.appa3.util;


import com.a2.appa3.global.Info;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.ByteString;

/**
 * Created by admin on 2018/12/24.
 * void	WebSocketListener.onClosed(WebSocket webSocket, int code, String reason)
 * Invoked when both peers have indicated that no more messages will be transmitted and the connection has been successfully released.
 * void	WebSocketListener.onClosing(WebSocket webSocket, int code, String reason)
 * Invoked when the remote peer has indicated that no more incoming messages will be transmitted.
 * void	WebSocketListener.onFailure(WebSocket webSocket, Throwable t, Response response)
 * Invoked when a web socket has been closed due to an error reading from or writing to the network.
 * void	WebSocketListener.onMessage(WebSocket webSocket, okio.ByteString bytes)
 * Invoked when a binary (type 0x2) message has been received.
 * void	WebSocketListener.onMessage(WebSocket webSocket, String text)
 * Invoked when a text (type 0x1) message has been received.
 * void	WebSocketListener.onOpen(WebSocket webSocket, Response response)
 * Invoked when a web socket has been accepted by the remote peer and may begin transmitting messages.
 */

public class WebSocketUtils2 {
    private static volatile WebSocketUtils2 uniqueinstance;
    private static WebSocket mSocket;
    private static MsgHandle mmsghanlde;
    private static int count = 3;
    public static String murl;
    public static int states = 0;//0 失败重试  //1不重试

    public static WebSocketUtils2 getInstance() {
        if (uniqueinstance == null) {
            synchronized (WebSocketUtils2.class) {
                if (uniqueinstance == null) {
                    uniqueinstance = new WebSocketUtils2();
                }
            }
        }
        return uniqueinstance;
    }

    public static void initWebsocket(String url, MsgHandle handle) {
        murl = url;
        mmsghanlde = handle;
        mmsghanlde.onBeginconnect();
        OkHttpClient mOkHttpClient = new OkHttpClient.Builder()
                .readTimeout(5, TimeUnit.SECONDS)//设置读取超时时间
                .writeTimeout(5, TimeUnit.SECONDS)//设置写的超时时间
                .connectTimeout(5, TimeUnit.SECONDS)//设置连接超时时间
                .build();
        Request request = new Request.Builder().url(url).build();
        EchoWebSocketListener socketListener = new EchoWebSocketListener();
        mOkHttpClient.newWebSocket(request, socketListener);
        mOkHttpClient.dispatcher().executorService().shutdown();
    }

    public interface MsgHandle {
        void open();

        void getMsg(String msg);

        void onClosed();

        void onFailure();

        void onBeginconnect();
    }

    private static class EchoWebSocketListener extends WebSocketListener {
        @Override
        public void onOpen(WebSocket webSocket, Response response) {
            super.onOpen(webSocket, response);
            mSocket = webSocket;
            mmsghanlde.open();
        }

        @Override
        public void onMessage(WebSocket webSocket, ByteString bytes) {
            super.onMessage(webSocket, bytes);
        }

        @Override
        public void onMessage(WebSocket webSocket, String text) {
            super.onMessage(webSocket, text);
            mmsghanlde.getMsg(text);
        }

        @Override
        public void onClosed(WebSocket webSocket, int code, String reason) {
            super.onClosed(webSocket, code, reason);
            mmsghanlde.onClosed();
        }

        @Override
        public void onClosing(WebSocket webSocket, int code, String reason) {
            super.onClosing(webSocket, code, reason);
        }

        @Override
        public void onFailure(WebSocket webSocket, Throwable t, Response response) {
            super.onFailure(webSocket, t, response);
            mmsghanlde.onFailure();
            if (mSocket != null) {
                mSocket.close(1000, "");
            }
            //然后开始重新连接
            if (states == 0) {
                initWebsocket(murl, mmsghanlde);
            } else if (states == 1) {
                //这里失败后不重试
            }
        }
    }

    public void sendMsg(String text) {
        boolean isok = mSocket.send("token=" + Info.user.token + "&" + text);
        SYSOUtils.sOut_("发送成功+++++++++++++++++++++++");
    }

    public void ondestoryWebsocket() {
        if (mSocket != null) {
            mSocket.close(1000, "");
            mSocket = null;
        }
    }
}
